package main

import (
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/julienschmidt/httprouter"
)

// testPageHandler 用来测试API上传视频用
func testPageHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// 模板路径
	t, _ := template.ParseFiles("./videos/upload.html")
	t.Execute(w, nil)
}

// streamHandler 获取视频(播放)
func streamHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	vid := p.ByName("vid-id") // 获取参数中的id
	vl := VIDEO_DIR + vid
	log.Printf("dir:%v", vl)
	video, err := os.Open(vl)
	if err != nil {
		log.Printf("open video file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal server error")
		return
	}
	// 解析视频
	w.Header().Set("Content-Type", "video/mp4")
	http.ServeContent(w, r, "", time.Now(), video) // 播放
	defer video.Close()
	/*
		使用阿里云oss url: 使用下面代码，上面可全部删除
		targetUrl:="http://xxxx"+p.ByName("vid-id")
		http.Redirect(w,r, targetUrl,301)
	*/

}

// uploadHandler 上传视频
func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE) // 上传大小
	if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
		log.Printf("file size too big: %v", err)
		sendErrorResponse(w, http.StatusBadRequest, "file size too big")
		return
	}
	file, _, err := r.FormFile("file") // 获取文件 表单的name值
	if err != nil {
		log.Printf("get file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "file upload internal error")
		return
	}
	data, err := ioutil.ReadAll(file) // 读取视频
	if err != nil {
		log.Printf("read file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "internal server error")
		return
	}
	fn := p.ByName("vid-id")
	err = ioutil.WriteFile(VIDEO_DIR+fn, data, 0666)
	if err != nil {
		log.Printf("Write file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "internal server error")
		return
	}
	/*
		阿里云oss go的sdk
		https://github.com/aliyun/aliyun-oss-go-sdk
		添加对应的代码
	*/
	w.WriteHeader(http.StatusCreated) //201
	io.WriteString(w, "Uploaded successfully")

}
